package com.eg366.nioLearn.baseSocket.chapter03.votetest;

/**
 * 程序支持两种请求。
 * （1）查询请求：向服务器查询指定候选人当前获得的投票总数；服务器返回的响应，包含候选人ID和候选人当前的得票数
 * （2）投票请求：向指定候选人投一票。服务器返回：候选人ID和得票数。
 */
public class VoteMsg {
	private boolean isInquiry; // true:查询 false:投票
	private boolean isResponse; // 响应or请求
	private int candidateID; // 投票ID [0,1000]
	private long voteCount; // 总得票数

	public static final int MAX_CANDIDATA_ID = 1000;

	public VoteMsg(boolean isResponse, boolean isInquiry, int candidateID,
			long voteCount) {
		// check
		if (voteCount != 0 && !isResponse) {
			throw new IllegalArgumentException(
					"Request vote count must be zero");
		}
		if (candidateID < 0 || candidateID > MAX_CANDIDATA_ID) {
			throw new IllegalArgumentException("Bad Candidate ID: "
					+ candidateID);
		}
		if (voteCount < 0) {
			throw new IllegalArgumentException("Total must be >= zero");
		}
		this.candidateID = candidateID;
		this.isResponse = isResponse;
		this.isInquiry = isInquiry;
		this.voteCount = voteCount;
	}

	public void setInquiry(boolean isInquiry) {
		this.isInquiry = isInquiry;
	}

	public void setResponse(boolean isResponse) {
		this.isResponse = isResponse;
	}

	public boolean isInquiry() {
		return this.isInquiry;
	}

	public boolean isResponse() {
		return this.isResponse;
	}

	public void setCandidateID(int candidateID) {
		if (candidateID < 0 || candidateID > MAX_CANDIDATA_ID) {
			throw new IllegalArgumentException("Bad Candidate ID: "
					+ candidateID);
		}
		this.candidateID = candidateID;
	}

	public int getCandidateID() {
		return candidateID;
	}

	public void setVoteCount(long voteCount) {
		if ((voteCount != 0 && !isResponse) || voteCount < 0) {
			throw new IllegalArgumentException("Bad vote count");
		}
		this.voteCount = voteCount;
	}

	public long getVoteCount() {
		return voteCount;
	}

	public String toString() {
		String res = (isInquiry ? "inquiry" : "vote") + " for candidate "
				+ candidateID;
		if (isResponse) {
			res = "response to " + res + " who now has " + voteCount
					+ " vote(s)";
		}
		return res;
	}
}
